package com.atguigu.tingshu.album.service;

import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.common.config.redis.RedisConfig;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: atguigu
 * @create: 2024-04-20 09:15
 */
@Slf4j
@Component
public class BloomFilterService {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private AlbumInfoMapper albumInfoMapper;

    /**
     * 布隆过滤器检查数量及扩容
     */
    public void resizeBloomFilter() {
        //1.查询布隆过滤器是否满足扩容条件
        //1.1 获取布隆过滤器对象
        RBloomFilter<Long> oldBloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
        //1.2 获取布隆过滤器元素数量
        long count = oldBloomFilter.count();
        //1.3 判断是否满足扩容条件
        //1.3.1 实际判断元素格式大于原有期望数据规模
        //if (count > oldBloomFilter.getExpectedInsertions()) {
        //    //2.对原有布隆过滤器进行扩容
        //}
        //1.3.2 方便测试判断元素个数大于500
        if (count > 500) {
            //2.对原有布隆过滤器进行扩容
            //2.1 创建初始化一个新布隆过滤器
            RBloomFilter<Long> newBloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER + ":new");
            newBloomFilter.tryInit(oldBloomFilter.getExpectedInsertions() * 2, 0.03);
            //2.2 查询现有发布成功专辑ID
            LambdaQueryWrapper<AlbumInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(AlbumInfo::getId);
            List<AlbumInfo> list = albumInfoMapper.selectList(queryWrapper);
            if (CollectionUtil.isNotEmpty(list)) {
                //2.3 遍历专辑ID将专辑ID存入新布隆过滤器
                for (AlbumInfo albumInfo : list) {
                    newBloomFilter.add(albumInfo.getId());
                }
                //2.4 删除原有布隆过滤器
                oldBloomFilter.delete();
                //2.4 对新布隆过滤器进行重命名
                newBloomFilter.rename(RedisConstant.ALBUM_BLOOM_FILTER);
            }
        }

    }
}
